# -*- coding:utf-8 -*-
import codecs
import shutil

__author__ = 'chenss'

import os
import sys

import chardet
print(sys.getdefaultencoding())


def convert(filename,new_filename,in_enc="gbk",out_enc="utf-8"):
    try:
        print("convert " + filename)
        content = open(filename,'rb').read()
        result = chardet.detect(content)  # 通过chardet.detect获取当前文件的编码格式串，返回类型为字典类型
        coding = result.get('encoding')  # 获取encoding的值[编码格式]
        if not coding: return
        if coding != out_enc:  # 文件格式如果不是utf-8的时候，才进行转码
            print(coding + " to "+out_enc)
            temp_in_enc=in_enc
            if("gbk"==coding):temp_in_enc=coding
            if("GB2312"==coding):temp_in_enc='gbk' #繁体中文需要用GBK编码
            if("UTF-8-SIG"==coding):temp_in_enc=coding #utf-8 bom，直接用原编码
            new_content = content.decode(temp_in_enc, 'ignore')#忽略乱码

            with codecs.open(new_filename, mode='w',encoding=out_enc) as f:
                f.write(new_content)  # 写入utf-8编码

            # b_str = bytes(new_content, encoding=out_enc)  # 转换成utf-8字节
            # with open(new_filename, mode='w',encoding=out_enc) as f:
            #     f.write(b_str.decode())#写入utf-8编码

        else:
            print(coding)
            shutil.copyfile(filename, new_filename) #utf-8编码的直接copy

    except IOError:
        print(" error")
    # else:
    #     print("else error")


def explore(dir,toDir,suffix):
    sfx=suffix.split(";")
    for root, dirs, files in os.walk(dir):
        for file in files:
            isIn=0
            for s in sfx:
              if file.lower().endswith(s):
                  isIn=1
                  break
            if isIn==0:continue
            path = os.path.join(root, file)
            newdir = root.replace(dir, toDir)
            if not os.path.exists(newdir):os.makedirs(newdir)
            newpath = os.path.join(newdir, file)
            print("path:" + path + ",newpath:" + newpath)
            convert(path,newpath)


def main():
    # for path in sys.argv[1:]:
    #     if os.path.isfile(path):1
    #         convert(path)
    #     elif os.path.isdir(path):
    #         explore(path)
	
	explore(r'D:\workspace\emas',r'D:\workspace\emas_utf-8',".jsp;.css;.js;.jsp;.htm;.html;.xml;.java")
	
    # explore(r'D:\workspace\emas\WEB-INF\src\com\jiaying\file',r'D:\python-workspace\Test1\conver')
    # explore(r'D:\workspace\emas\WEB-INF\src',r'D:\workspace\emas_utf-8\WEB-INF\src',".java") #java
    # explore(r'D:\workspace\emas',r'D:\workspace\emas_utf-8',".jsp;.css;.js;.jsp;.htm;.html;.xml")
    # explore(r'D:\workspace\emas\hk'.replace("\u202a","")
    #         ,r'D:\workspace\emas_utf-8\hk',".jsp;.css;.js;.jsp;.htm;.html") #

    #test()


def test():
    filename = r'D:\workspace\emas\js\easyui\themes\black\numberbox.css'
    # filename = r'D:\python-workspace\Test1\sms_status_sql.py'
    filename = r'D:\workspace\emas\js\ui\jquery.validate.js'
    content = open(filename.replace("\u202a",""), 'rb').read()
    result = chardet.detect(content)  # 通过chardet.detect获取当前文件的编码格式串，返回类型为字典类型
    coding = result.get('encoding')  # 获取encoding的值[编码格式]
    print(coding)
    if not coding:
        print("is None")
    else:
        print("xxxx "+coding)
        # coding="gbk"
        coding="ISO-8859-1"
        new_content = content.decode(coding, 'ignore')  # 忽略乱码
        print("new_content->"+new_content)



if __name__ == "__main__":
    main()
